package cn.edu.zust.se.mvcdb.filter;

import cn.edu.zust.se.mvcdb.vo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter(filterName = "authFilter",urlPatterns = "/*")
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        User u=(User)req.getSession().getAttribute("user");
        String uri=((HttpServletRequest) servletRequest).getRequestURI();
        System.out.println("请求"+uri+"被过滤");
        if(uri.startsWith("/login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            System.out.println(uri+"被放过");
            return;
        }
        if(u==null)
            req.getRequestDispatcher("login.jsp").forward(servletRequest,servletResponse);
        else
            filterChain.doFilter(servletRequest,servletResponse);
    }
}
